// pages/device/home.js
// 设备状态
import * as echarts from '../../../ec-canvas/echarts';

var bluetooth = require('../../../command/bluetooth.js')
var app = getApp()
var cmd = require('../../../command/command.js')

var mychart;
var option = {
  backgroundColor: "#40A1D9",
  color: "red",
  series: [{
    name: '电机电压',
    type: 'gauge',
    detail: {
      formatter: '{value}V'
    },
    axisLine: {
      show: true,
    },
    data: [{
      value: 0,
    }],
    min: 0,
    max: 40,
    radius: '70%',
    center: ['50%', '50%'],
  }]
};


function initChart(canvas, width, height, dpr) {
  mychart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(mychart);
  mychart.setOption(option, true);

  return mychart;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    ec: {
      onInit: initChart
    },
    imageSrc: 'https://ytouch-1258011219.cos.ap-nanjing.myqcloud.com/logo_copy.png',
    machineStartText: "启动", //
    machineAutoText: "自动",
    machineState: "",
    machineSpeed: 3000, //速度
    machineMode: "", //模式 标准模式，节能模式，充电模式，自定义
    machinePower: 0, //功率
    machineErrorState:"0000",
    isMachineRunning: false,
    isStartTimerRunning: false, 
    isStopTimerRunning: false,
    stopHour : 0,
    stopMin : 0,
    timerContralBit:"",
    value: 'label_1',
    list: [{
        value: 'label_1',
        label: '设备状态',
        icon: 'pin'
      },
      {
        value: 'label_2',
        label: '设备参数',
        icon: 'app'
      },
      {
        value: 'label_3',
        label: '参数页面',
        icon: 'chat'
      },
    ],
  },
  refleshId: null,
  sendCmdId: null,
  checkUpdateId: null,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("home.js onLoad")

    app.getCmdDescTable()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    console.log("设备状态OnShow")
    this.setData({
      value: 'label_1',
    })

    wx.setNavigationBarTitle({
      title: "已连接 " + app.globalData.bluetoothName
    })
    
    var first = true
    //先自动检查更新
    this.checkUpdateId = setInterval(() => {
      if (first == true && app.globalData.isReStartUpdate == true) {
        clearInterval(this.refleshId)
        clearInterval(this.sendCmdId)
        clearInterval(this.checkUpdateId)
        first = false
        console.log("current-Page-Length:",getCurrentPages().length)
        if(getCurrentPages().length > 8)
        {
          wx.reLaunch({
            url: '../update/update',
            })
        }
        else{
          wx.navigateTo({
            url: '../update/update',
            })
        }
        
      }
    }, 50)

    //把所有指令的接收状态置为true，保证初次updateData时能刷新
    cmd.resetRecDataState()

    //定时刷新页面数据
    this.refleshId = setInterval(() => {
      if(!this.isCurPage())
        return
      this.updateData()
    }, 200);

    this.sendCmdId = setInterval(() => {
      if(!this.isCurPage())
        return

      if(!app.globalData.connected){
        return
      }
      
      this.data.machineErrorState = "0000"
      var comandArray = ["controllerOutVoltage", 
      "machineWorkState",
      "machineErrorState",
      "machineSpeed",
      "controllerOutCurrent",
      "machineMode",
      "stopTimeHour",
      "stopTimeMin",
      "startTimeHour",
      "startTimeMin",
      "timerContralBit"]
      for(var i = 0; i < comandArray.length; i++){
        bluetooth.send(cmd.getCommandByName(comandArray[i]))
      }
    }, 2000);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log("home.js onHide")
    clearInterval(this.refleshId)
    clearInterval(this.sendCmdId)
    clearInterval(this.checkUpdateId)
  },

  onChange(e) {
    this.setData({
      value: e.detail.value,
    });
    if (e.detail.value == "label_1") {
      // wx.navigateTo({
      //   url: '../home/home',
      // })
    } else if (e.detail.value == "label_2") {
          console.log("current-Page-Length:",getCurrentPages().length)
          if (getCurrentPages().length > 8)
          {
            wx.reLaunch({
              url: '../writesetting/writesetting',
            })
            
          }
          else{
            wx.navigateTo({
              url: "../writesetting/writesetting",
            })
          }

    } else {
          console.log("current-Page-Length:",getCurrentPages().length)
          if (getCurrentPages().length > 8)
          {
            wx.reLaunch({
              url: "../state/state",
            })
            
          }
          else{
            wx.navigateTo({
              url: "../state/state",
            })
          }
    }
    // setTimeout(()=>{
    //   this.setData({
    //     value: "label_1",
    //   })
    // }, 1000);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log("home.js onUnload")
    clearInterval(this.refleshId)
    clearInterval(this.sendCmdId)
    clearInterval(this.checkUpdateId)
  },

  /**
   * 启动/停止
   */
  goStartMachine() {
    console.log("goStartMachine")
    if (this.data.isMachineRunning == false) {
      bluetooth.send(cmd.getCommandByName("start"))
    } else {
      bluetooth.send(cmd.getCommandByName("stop"))
    }
  },
  /*
   * 进入到新的页面
   */
  goTogglePage() {
        console.log("current-Page-Length:",getCurrentPages().length)
    if(getCurrentPages().length > 8)
    {
      wx.reLaunch({
        url: '../toggle/toggle',
      })
      
    }
    else{
      wx.navigateTo({
        url: "../toggle/toggle",
      })
    }
  },
  /**
   * 自动/手动
   */
  goAutoMachine() {
    console.log("goAutoMachine")

    if(this.data.machineErrorState != "0000"){
          console.log("current-Page-Length:",getCurrentPages().length)
          if (getCurrentPages().length > 8)
          {
            wx.reLaunch({
              url: '../report/report',
            })
            
          }
          else{
            wx.navigateTo({
              url: '../report/report',
            })
          }
    }
    bluetooth.send(cmd.getCommandByName("switchAuto"))
  },
  /**
   * 拉盘
   */
  goLapanMachine() {
    console.log("goLapanMachine")

    // wx.navigateTo({
    //   url: "../update/update",
    // })
  },
  /**
   * 设备状态页面
   */
  goMachineState() {
    console.log("goMachineState")
    // wx.navigateTo({
    //   url: "../state/state",
    // })
    this.isAutoSend = true
  },
  /**
   * 设置参数页面
   */
  goSetMachine() {
        console.log("current-Page-Length:",getCurrentPages().length)
        if(getCurrentPages().length > 8)
        {
          wx.reLaunch({
            url: '../writesetting/writesetting',
          })
          
        }
        else{
          wx.navigateTo({
            url: "../writesetting/writesetting",
          })
        }
  },
  /**
   * 参数页面
   */
  goMachineSetting() {
        console.log("current-Page-Length:",getCurrentPages().length)
        if(getCurrentPages().length > 8)
        {
          wx.reLaunch({
            url: '../state/state',
          })
          
        }
        else{
          wx.navigateTo({
            url: "../state/state",
          })
        }
  },

  isCurPage(){
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    return currentPage.route === 'pages/device/home/home';    
  },
  /**
   * 
   */
  updateData() {
    if(!this.isCurPage())
        return

    const valtage = cmd.getRecDataValueByName("controllerOutVoltage")
    const machineState = cmd.getRecDataValueByName("machineWorkState")
    const machineErrorState = cmd.getRecDataValueByName("machineErrorState")
    const _machineSpeed = cmd.getRecDataValueByName("machineSpeed")
    const _machineCurrent = cmd.getRecDataValueByName("controllerOutCurrent")
    const _machineValtage = cmd.getRecDataValueByName("controllerOutVoltage")
    const _machineMode = cmd.getRecDataValueByName("machineMode")
    const _stopTimeHour = cmd.getRecDataValueByName("stopTimeHour")
    const _stopTimeMin = cmd.getRecDataValueByName("stopTimeMin")
    const _startTimeHour = cmd.getRecDataValueByName("startTimeHour")
    const _startTimeMin = cmd.getRecDataValueByName("startTimeMin")
    const _timerContralBit = cmd.getRecDataValueByName("timerContralBit")
    // console.log(machineErrorState)

    if (valtage != null && option.series[0].data[0].value != valtage) {
      option.series[0].data[0].value = Number(valtage).toFixed(2)
      mychart.setOption(option)
    }

    //故障检查
    if(machineErrorState != null && this.data.machineErrorState != machineErrorState){
      console.log(cmd.EngineFaultFode(machineErrorState))
      this.data.machineErrorState = machineErrorState
    }

    //检查按键状态
    if (machineState != null && this.data.machineState != machineState) {
      this.data.machineState = machineState

      console.log(cmd.getHomeFaceStatus())
      this.setData({
        machineAutoText: cmd.getHomeFaceStatus()
      })

      if(cmd.getMachineStatus()){
        console.log("正在运行")
        this.data.isMachineRunning = true
        this.setData({
          machineStartText: "停止",
        })
      } else {
        console.log("停止状态")
        this.data.isMachineRunning = false
        this.setData({
          machineStartText: "启动",
        })
      }
    }

    if(this.data.machineErrorState != "0000"){
      console.error("发动机故障", cmd.EngineFaultFode(machineErrorState))
      this.setData({
        machineAutoText: "故障说明",
      })
    }
    
    // 定时器状态判断
    if(_timerContralBit != null && this.data.timerContralBit != _timerContralBit)
    {
      this.data.timerContralBit = _timerContralBit
      var state = this.data.timerContralBit

      this.data.isStartTimerRunning = false
      this.data.isStopTimerRunning = false

      if ((state & 0x0001) !== 0) { //定时停在工作
        this.data.isStopTimerRunning = true
      }

      if ((state & 0x0002) !== 0) { //定时启在工作
        this.data.isStartTimerRunning = true
      }

      if ((state & 0x0004) !== 0) { //休眠在工作
      }
    }
    
    var _showTimer = false
    var stopDec, _stopHour, _stopMin;
    if(this.data.isMachineRunning){
      stopDec = "停机"
      _stopHour = _stopTimeHour
      _stopMin = _stopTimeMin
      if(this.data.isStopTimerRunning){
        _showTimer = true
      }
    }else{
      stopDec = "启动"
      _stopHour = _startTimeHour
      _stopMin = _startTimeMin
      if(this.data.isStartTimerRunning){
        _showTimer = true
      }
    }

    this.setData({
      stopStatus: stopDec,
      stopHour: _stopHour,
      stopMin: _stopMin,
      showTimer : _showTimer
    })
    
    //模式：标准、节能、充电、自定义（自定义不显示）
    var modeName = "未定义";
    switch(_machineMode){
      case 1:modeName = "节能模式";break;
      case 2:modeName = "标准模式";break;
      case 3:modeName = "充电模式";break;
      case 4:modeName = "自定义模式";break;
    }

    this.setData({
      machineSpeed: _machineSpeed === null ? 0 : _machineSpeed, //转速
      machinePower : (_machineCurrent * _machineValtage).toFixed(1), //功率
      machineMode : modeName,
    })
  },
})